const { User } = require("../models/userModel");
const jwt = require('jsonwebtoken');
const { search } = require("../routes/user");
const {
    uploadFiles,
    moveFiles,
    removeFiles
} = require("../utils/upload"); //图片上传需要

//添加用户
async function addUser(req, res) {
    console.info(req.body)
    const { account, password, avatar, phone, realName, role } = req.body
    const userAlreadyExists = await User.find({
        account
    })
    console.log('aaa',userAlreadyExists);
    if (userAlreadyExists.length > 0) {
        res.send({
            status: 0,
            msg: "用户名已经存在，请尝试其他用户名"
        })
    } else {
        if (avatar&&avatar!="default.jpg") { //判断头像存在与否，存在将缓存区的图片放在图片路径中,且将缓存区的文件夹删除
            moveFiles({
                fromPath: "./public/temp",
                toPath: "./public/images",
                filename: avatar
            });
            removeFiles("./public/temp");
            await User.create({
                account, password, avatar, phone, realName, role
            })
            res.send({
                status: 1,
                msg: "注册成功",
                data: {
                    account, password
                }
            })
        }
        await User.create({
            account, password, avatar, phone, realName, role
        })
        res.send({
            status: 1,
            msg: "注册成功",
            data: {
                account, password
            }
        })
    }
}

//软删除用户
async function delUser(req, res) {
    const { _id } = req.body
    await User.updateOne({
        _id
    }, { deleted: true })
    res.send({
        status: 1,
        msg: "成功删除用户"
    })
}

//用户登录
async function login(req, res) {
    const { account, password } = req.body
    const userExists = await User.find({ account })
    if (userExists.length > 0) {
        let gotUser = userExists[0]
        if (gotUser.password == password) {
            if (gotUser.frozen || gotUser.deleted) {
                res.send({
                    status: 0,
                    msg: "用户已被冻结或删除",
                })
            } else {
                const token = jwt.sign(
                    { account },//保存用户信息
                    'xiaoyunpeng',//编码字符串
                    { expiresIn: 60 * 60 } //token有效期
                );
                res.send({
                    status: 1, 
                    data: {
                        _id: gotUser._id,
                        token
                    },
                    msg: "登陆成功"
                })
            }
        } else {
            res.send({
                status: 0,
                msg: "登陆失败，密码不正确",
            })
        }
    } else {
        res.send({
            status: 0,
            msg: "用户不存在"
        })
    }
}


//修改用户信息
async function changeUserInfo(req, res) {
    console.info(req.body)
    const { _id, account, avatar, phone, password,role } = req.body
    //判断头像存在与否，存在将缓存区的图片放在图片路径中,且将缓存区的文件夹删除


    // if (avatar) {
    //     moveFiles({
    //         fromPath: "./public/temp",
    //         toPath: "./public/images",
    //         filename: avatar
    //     });
    //     removeFiles("./public/temp");
    // }
    await User.updateOne({ _id }, { account, avatar,password, phone, role })

    res.send({
        msg: "修改用户信息成功",
        status: 1,
    })
}


//获取所有用户
async function getAllUsers(req, res) {
    const { searchType = "", pageSize = 100, currentPage = 1 } = req.body
    let total = await User.countDocuments()
    let totalPages = Math.ceil(total / pageSize)
    if (searchType == "") {
        let gotUsers = await User.find().limit(pageSize - 0).skip((currentPage - 1) * pageSize)
        res.send({
            status: 1,
            msg: "获取用户信息成功",
            data: {
                gotUsers,
                total,
                currentPage,
                pageSize,
                totalPages
            }
        })
    } else {
        let gotUsers = await User.find({ role: searchType }).limit(pageSize - 0).skip((currentPage - 1) * pageSize)
        res.send({
            status: 1,
            msg: "获取用户信息成功",
            data: {
                gotUsers,
                total,
                currentPage,
                pageSize,
                totalPages
            }
        })
    }
}

//根据ID获取用户
async function getUserByID(req, res) {
    const { _id } = req.body
    let gotUser = await User
    .find({ _id })
    .populate({
        path: 'ownerOrders',
        populate: { path: 'carID' },
    })
    .populate({
        path: 'customerOrders',
        populate: { path: 'carID' },
    })
    .populate("cars")
    if(gotUser.length>0){
        res.send({
            status: 1,
            msg: "获取用户信息成功",
            data: {
                gotUser
            }
        })
    }else{
        res.send({
            status:0,
            msg:"没有找到该用户",
        })
    }
   
}

//账户充值
async function changeBalance(req, res) {
    const { _id, chargeAmount } = req.body
    const gotUser = await User.find({ _id })
    console.info(gotUser)
    const currentBalance = gotUser[0].balance
    const newBalance = currentBalance + (chargeAmount - 0)
    await User.updateOne({ _id }, { balance: newBalance })
    res.send({
        status: 1,
        msg: `账户余额更新为：${newBalance}元`,
        data: { newBalance }
    })
}
//what the fuck? number + number = string?

//用户提交实名验证
async function verifyID(req, res) {
    const { _id, identity } = req.body
    await User.updateOne({ _id }, { identity, idVerified: 2 })
    res.send({
        status: 1,
        msg: "身份信息提交成功，等待审核"
    })
}

//审核通过实名认证，不点确定根本不会发到这个接口
async function approveID(req, res) {
    const { _id } = req.body
    await User.updateOne({ _id }, { idVerified: 1 })
    res.send({
        status: 1,
        msg: "身份信息审核通过"
    })
}

//审核拒绝实名认证，清空用户提交的实名认证信息，并把实名认证状态修改回0（未认证）
async function rejectID(req, res) {
    const { _id } = req.body
    await User.updateOne({ _id }, { identity: "", idVerified: 0 })
    res.send({
        status: 1,
        msg: "身份信息审核已拒绝，用户实名认证信息已重置"
    })
}


//修改账户冻结状态

async function changeFrozenStatus(req, res) {
    const { _id, status } = req.body
    await User.updateOne({ _id }, { frozen: status })
    if (status) {
        res.send({
            status: 1,
            msg: "已冻结用户"
        })
    } else {
        res.send({
            status: 1,
            msg: "已解冻用户"
        })
    }

}

//将车辆添加到愿望单
async function addCarToWishlist(req, res) {
    const { _id, carID } = req.body
    await User.findByIdAndUpdate(_id, { $push: { wishilist: carID } })
    res.send({
        status: 1,
        msg: "添加到愿望单成功"
    })
}

//添加用户头像
async function uploadUserAvatar(req, res) {
    const images = uploadFiles({
        path: "./public/temp"
    }); //路径以app.js作为参考
    images(req, res, (err) => {
        if (err) {
            console.info("上传失败" + err)
        } else {
            res.send({
                status: 1,
                massage: "上传成功",
                data: req.files[0].filename //将图片的路径返回去
            })
        }
    })
}


////
module.exports = { addUser, delUser, login, changeUserInfo, getAllUsers, getUserByID, changeBalance, verifyID, approveID, rejectID, changeFrozenStatus, addCarToWishlist, uploadUserAvatar }